
package SSF.OS;

import com.renesys.raceway.SSF.*;

/** Wrapper class to turn a ProtocolMessage into an Event that can 
  * be sent on an SSF channel. 
  */
public class PacketEvent extends Event {
  private ProtocolMessage pkt;

/** Return the protocol message (the packet headers) inside this PacketEvent.*/
  public ProtocolMessage getHeaders() {
    return pkt;
  }

/** Create an empty PacketEvent with no headers. */
  public PacketEvent() {}

/** Create a PacketEvent wrapper for the given ProtocolMessage. */
  public PacketEvent(ProtocolMessage msg) {pkt = msg;}

/** Create an instance of the given class, which must extend ProtocolMessage,
  * and wrap it in a PacketEvent. 
  */
  public PacketEvent(Class pktclass) {
    try {
      pkt = (ProtocolMessage)pktclass.newInstance();
    }catch (Exception e) {
      System.err.println("**** Warning: "+e);
    }
  }

 
/** Deserialize a packet from a byte buffer. <b>Experimental.</b>*/
  public void frombytes(byte[] buf) {
    int offset = 0;
    if (pkt==null) 
      System.err.println("Cannot deserialize without a packet template");
    ProtocolMessage P = pkt;
    while (P != null) {
      P.frombytes(buf,offset);
      offset += P.bytecount();
      if (P.payload() == null && offset<buf.length) 
	System.err.println(//throw new PacketEventException(
	  "Deserialized packets must create tail header template");
      P = P.payload();
    }
  }

/** Convert a packet into a byte buffer. <b>Experimental.</b>*/
  public byte[] tobytes() {
    ProtocolMessage P = pkt;
    int bct = 0;
    while (P!=null) {
      bct += P.bytecount();
      P=P.payload();
    }
    byte[] buf = new byte[bct];
    P = pkt;
    int offset = 0;
    while (P!=null) {
      P.tobytes(buf,offset);
      offset += P.bytecount();
    }
    return(buf);
  }
}

/*=                                                                      =*/
/*=  Copyright (c) 1997--2000  SSF Research Network                      =*/
/*=                                                                      =*/
/*=  SSFNet is open source software, distributed under the GNU General   =*/
/*=  Public License.  See the file COPYING in the 'doc' subdirectory of  =*/
/*=  the SSFNet distribution, or http://www.fsf.org/copyleft/gpl.html    =*/
/*=                                                                      =*/
